package com.aube.plugin.origin;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.OvershootInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.episode.VideoWidget;
import com.aube.plugin.episode.list.VideoListActivity;
import com.aube.plugin.figure.CharacterActivity;
import com.aube.plugin.guide.WidgetGuide;
import com.aube.plugin.infinitevp.HorizontalInfiniteCycleViewPager;
import com.aube.plugin.previous.WidgetPrevious;
import com.aube.plugin.user.WidgetUserCenter;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.dynamicload.DLContentView;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DLProxyContext;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.PluginPackageManager;
import com.huyn.baseframework.dynamicload.PositionManageUtil;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.model.Character;
import com.huyn.baseframework.model.ThemeModel;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.statistics.AubeStatisticTool;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.SharedPrefUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;
import com.ryg.dynamicload.internal.DLIntent;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/10/9.
 */
public class OriginLauncher extends DLContentView {
    private final String TAG = "Aube/OriginLauncher";

    private static final int ANI_DURATION = 500;
    private static final float SCALE_INT = 1.2F;
    private static final int SPLASH_TIME = 3000;
    private static final int ERROR_TIME = 20000;
    private static final int SPLASH_ALPHA_ANIM_TIME = 500;
    private static final int USERLAYOUT_DURATION = 300;

    private static final int TYPE_VIEW = 1;
    private static final int TYPE_VIEWPAGER = 2;

    public static final String TEMPLATE_INDEX = "index";
    public static final String HEADER_INDEX = "indexHead";

    private FreeEventScrollView mScrollview;
    private LinearLayout mScrollLayout, mScrollContent;
    private LinearLayout mGuideLayout;
    private FrameLayout mUsercenterLayout, mUsercenterImgLayout;
    private ImageView mUsercenterImg;
    private FrameLayout mBgContainer;
    private View mBlurTop;

    private PluginPackageManager mPluginManager;

    private AtomicBoolean mThemeLoadLock = new AtomicBoolean(false);
    private HashMap<String, DLLayout> mDLLayouts = new HashMap<>();

    private PositionManageUtil mPositionManager;

    private DLLayout mUserLayout;

    private int targetHeight, screenHeight;
    private int mLastScrollY = 0;

    private BlurViewDecorator mBlurview;
    private View mSplash;

    private ScrollHeader mScrollHeader;
    private HorizontalInfiniteCycleViewPager mViewPager;

    private int mTypeBg = TYPE_VIEW;

    private AtomicBoolean mGuideShowing = new AtomicBoolean(false);
    private AtomicBoolean mGuideTargetInited = new AtomicBoolean(false);

    private String mFirstModule;

    public OriginLauncher(Context context) {
        this(context, null);
    }

    public OriginLauncher(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public OriginLauncher(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void initViews() {
        Utils.Log(TAG, "[initViews]");
        inflate(R.layout.layout_launcher, this, true);

        mScrollview = (FreeEventScrollView) findViewById(R.id.scrollview);
        mScrollLayout = (LinearLayout) findViewById(R.id.scroll_container);
        mScrollContent = (LinearLayout) findViewById(R.id.scroll_content);
        mGuideLayout = (LinearLayout) findViewById(R.id.guide_layout);
        mUsercenterLayout = (FrameLayout) findViewById(R.id.usercenter_layout);
        mUsercenterImgLayout = (FrameLayout) findViewById(R.id.usercenter_img_layout);
        mUsercenterImg = (ImageView) findViewById(R.id.usercenter_img);

        mBlurTop = findViewById(R.id.blurring_top);

        mUsercenterImgLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageUserCenter();
            }
        });

        setImgWithRes(mUsercenterImg, R.drawable.icon_grzx);
        setBgWithRes(mUsercenterImgLayout, R.drawable.bk_circle);
        setBgWithRes(mBlurTop, R.drawable.gradient_blur_top);

        mPluginManager = PluginPackageManager.getInstance();

        mPositionManager = new PositionManageUtil(mScrollview);

        mScrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int y = mScrollview.getScrollY();
                if (y == mLastScrollY)
                    return;
                mLastScrollY = y;

                if(mPositionManager != null)
                    mPositionManager.listener(y);

                int targetY = targetHeight - y;
                mBlurview.setTranslationY(targetY < 0 ? 0 : targetY);
                mBlurview.invalidate();
                mBlurTop.setTranslationY(targetY < 0 ? -targetHeight : -y);
            }
        });

        mScrollview.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(mGuideShowing.get())
                    return true;
                return false;
            }
        });

        mScrollview.setDispatchScrollListener(new FreeEventScrollView.IDispatchScrollListener() {
            @Override
            public boolean onTransparentLocation(MotionEvent ev) {
                if(!isBgAnViewPager())
                    return false;
                if(mLastScrollY >= targetHeight)
                    return false;
                float y = ev.getY();
                if(y < targetHeight - mLastScrollY)
                    return true;
                return false;
            }
        });
    }

    private void setupModules(HomeCategoryModel model) {
        Utils.Log(TAG, "[setupModules]");
        if(mPluginManager == null)
            return;
        if(model != null && model.success() && model.size() > 0) {
            mScrollContent.removeAllViews();
            if(mDLLayouts == null)
                mDLLayouts = new HashMap<>();
            int size = model.data.size();
            int index = 0;
            for(Category cate : model.data) {
                if(ModuleLauncher.isInThisPackage(cate.modelCode)) {
                    if(StringUtils.isBlank(mFirstModule))
                        mFirstModule = cate.modelCode;
                    cate.templateType = TEMPLATE_INDEX;
                    try {
                        Utils.Log(TAG, "[setupModules] modelCode = " + cate.modelCode + ", modelExtra = " + cate.modelExtra);
                        String modelStyle = (String) cate.getStrFromExtra("modelStyle");
                        if("actor".equalsIgnoreCase(cate.modelCode) && modelStyle != null && modelStyle.equalsIgnoreCase("team")) {
                            Utils.Log(TAG, "[setupModules] lucky. got in");
                            DLLayout view = DynamicLoaderHelper.loadTargetLayout(new DLProxyContext(context, getDLPluginPackage()), getDLPluginPackage(),
                                    "com.aube.plugin.figureex.FigureExWidget");
                            if (view != null) {
                                Utils.Log(TAG, "[setupModules] lucky. view not null");
                                mScrollContent.addView(view);
                                if (mPositionManager != null)
                                    view.registToManager(mPositionManager);
                                view.setDLBridge(mBridge);
                                view.fillData(cate);

                                mDLLayouts.put(cate.getModelCode(), view);

                                if (index != size - 1)
                                    addDivider();
                            } else {
                                Utils.Log(TAG, "[setupModules] unluck. view is null");
                                index--;
                            }
                        } else if("previous".equalsIgnoreCase(cate.modelCode)) {
                            Utils.Log(TAG, "[setupModules] lucky. got in");
                            DLLayout view = DynamicLoaderHelper.loadTargetLayout(new DLProxyContext(context, getDLPluginPackage()), getDLPluginPackage(), WidgetPrevious.class.getName());
                            if(view != null) {
                                Utils.Log(TAG, "[setupModules] lucky. view not null");
                                mScrollContent.addView(view);
                                if(mPositionManager != null)
                                    view.registToManager(mPositionManager);
                                view.setDLBridge(mBridge);
                                view.fillData(cate);

                                mDLLayouts.put(cate.getModelCode(), view);

                                if (index != size - 1)
                                    addDivider();
                            } else {
                                Utils.Log(TAG, "[setupModules] unluck. view is null");
                                index --;
                            }
                        } else {
                            DLLayout view = DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), ModuleLauncher.getClassName(cate.modelCode));

                            if (view != null) {
                                if(view instanceof VideoWidget && !mGuideTargetInited.get()) {
                                    mGuideTargetInited.set(true);
                                    ((VideoWidget) view).setIVideoGuideListener(new VideoWidget.IVideoGuideListener() {
                                        @Override
                                        public boolean shouldShowGuide() {
                                            Utils.sysout("shouldShowGuide::::mFirstModule=" + mFirstModule);
                                            if("episode".equalsIgnoreCase(mFirstModule))
                                                return SharedPrefUtil.getInstance(context).getBool(VideoWidget.GUIDE_DISPLAY_STATE, true);
                                            return false;
                                        }

                                        @Override
                                        public void guideFinished() {
                                            mGuideShowing.set(false);
                                        }

                                        @Override
                                        public void guideShowing() {
                                            mGuideShowing.set(true);
                                            SharedPrefUtil.getInstance(context).putBool(VideoWidget.GUIDE_DISPLAY_STATE, false);
                                        }
                                    });
                                }
                                mScrollContent.addView(view);
                                if(mPositionManager != null)
                                    view.registToManager(mPositionManager);
                                view.setDLBridge(mBridge);
                                view.fillData(cate);

                                mDLLayouts.put(cate.getModelCode(), view);

                                if (index != size - 1)
                                    addDivider();
                            } else {
                                index--;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Utils.Log(TAG, "[setupModules] exception : " + e);
                        index--;
                    }
                } if(mPluginManager.hasModule(cate.modelCode) && cate.size() > 0) {
                    if(StringUtils.isBlank(mFirstModule))
                        mFirstModule = cate.modelCode;
                    cate.templateType = TEMPLATE_INDEX;
                    try {
//                        DLLayout view = mPluginManager.inflatePluginLayout(context, cate.modelCode, cate.launchclass, true);
                        DLLayout view = mPluginManager.inflatePluginLayout(context, cate.modelCode, ModuleLauncher.getLaunchClass(cate.modelCode), true);

                        if (view != null) {
                            mScrollContent.addView(view);
                            if(mPositionManager != null)
                                view.registToManager(mPositionManager);
                            view.setDLBridge(mBridge);
                            view.fillData(cate);

                            mDLLayouts.put(cate.getModelCode(), view);

                            if (index != size - 1)
                                addDivider();
                        } else {
                            index--;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        index--;
                    }
                } else if(HEADER_INDEX.equalsIgnoreCase(cate.modelCode)) {
                    setupIndexHeader(DataConvertUtil.parseIndexHeader(cate.dataDetail));
                }
                index++;
            }

            initGuideLayout();

            fillUserCenter();

            synchronized (mThemeLoadLock) {
                if(mThemeLoadLock.get()) {
                    springOut();
                } else {
                    mThemeLoadLock.set(true);
                }
            }
        }
    }

    private void fillUserCenter() {
        mUserLayout = DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), WidgetUserCenter.class.getName());
        if (mUserLayout != null) {
            mUsercenterLayout.addView(mUserLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mUserLayout.setDLBridge(mBridge);
            mUserLayout.attachViews(mUsercenterImgLayout);
        }
    }

    private void initGuideLayout() {
        if(!WidgetGuide.ifNeedShowGuide(context))
            return;
        WidgetGuide view = (WidgetGuide) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), WidgetGuide.class.getName());

        if (view != null) {
            mGuideLayout.addView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setGuideListener(new WidgetGuide.IGuideListener() {
                @Override
                public void dismiss() {
                    onGuideDismiss();
                }
            });
        }
    }

    public void setupIndexHeader(List<DataConvertUtil.SimpleIndexHeader> data) {
        screenHeight = SysUtil.getAbsoluteScreenHeight(context);
        targetHeight = SysUtil.getAbsoluteScreenWidth(context)*4/5;//screenHeight*3/5 + SysUtil.getStatusHeight(context);

        mScrollHeader = (ScrollHeader) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), ScrollHeader.class.getName());
        if(data != null && data.size() > 0) {
            if (data.size() > 1) {
                fillMultiple(data);
                mBlurTop.setVisibility(View.GONE);
            } else {
                DataConvertUtil.SimpleIndexHeader simpleIndexHeader = data.get(0);
                if (simpleIndexHeader != null) {
                    mScrollHeader.fillData(simpleIndexHeader, mBridge);

                    if (simpleIndexHeader.isH5()) {
                        mBlurTop.setVisibility(View.GONE);
                    }
                }
                fillVideo(simpleIndexHeader);
            }
        }
        mScrollLayout.addView(mScrollHeader, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, targetHeight));

        RelativeLayout.LayoutParams topParams = (RelativeLayout.LayoutParams) mBlurTop.getLayoutParams();
        topParams.height = targetHeight;
        mBlurTop.setAlpha(0f);

        mScrollview.setVisibility(View.VISIBLE);
        mScrollview.setTranslationY(mScrollview.getHeight());

        mUsercenterImgLayout.setVisibility(View.VISIBLE);
        mUsercenterImgLayout.setTranslationY(mUsercenterImgLayout.getHeight() + getResources().getDimensionPixelOffset(R.dimen.userimg_bottom_margin));
    }

    private void fillVideo(final DataConvertUtil.SimpleIndexHeader simpleIndexHeader) {
        mTypeBg = TYPE_VIEW;
        final ImageView mImg = new ImageView(context);
        mImg.setScaleType(ImageView.ScaleType.CENTER_CROP);
        mBgContainer.addView(mImg, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        ImageLoader.getInstance(context).preloadBitmap(simpleIndexHeader.picurl, new ImageLoader.IPreloadCallback<Bitmap>() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                mImg.setImageBitmap(bitmap);
                ObjectAnimator anim = ObjectAnimator.ofFloat(mSplash, "alpha", 1, 0);
                anim.setDuration(SPLASH_ALPHA_ANIM_TIME);
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        mBlurview.invalidate();
                    }
                });
                anim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mSplash.setVisibility(View.GONE);
                    }
                });
                anim.start();
            }

            @Override
            public void onFail() {

            }
        });
    }

    private void fillMultiple(List<DataConvertUtil.SimpleIndexHeader> data) {
        mTypeBg = TYPE_VIEWPAGER;
        mViewPager= new HorizontalInfiniteCycleViewPager(context);
        mBgContainer.addView(mViewPager, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        mViewPager.setAdapter(new HorizontalPagerAdapter(getContext(), getResources(), mBridge, data));

        ObjectAnimator anim = ObjectAnimator.ofFloat(mSplash, "alpha", 1, 0);
                anim.setDuration(SPLASH_ALPHA_ANIM_TIME);
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        mBlurview.invalidate();
                    }
                });
                anim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mSplash.setVisibility(View.GONE);
                    }
                });
                anim.start();
    }

    private boolean isBgAnViewPager() {
        return mTypeBg == TYPE_VIEWPAGER;
    }

    private void updateTheme() {
        if(mDLLayouts == null)
            return;
        int color = getResources().getColor(R.color.theme);
        ThemeModel theme = mPluginManager.getTheme();
        if(theme != null) {
            int themeColor = theme.getThemeColor();
            if (themeColor != 0)
                color = themeColor;
        }
        updatePluginTheme(color);
        if(mUserLayout != null)
            mUserLayout.setTheme(color);
    }

    private void updatePluginTheme(int color) {
        Iterator<DLLayout> iterator = mDLLayouts.values().iterator();
        while (iterator.hasNext()) {
            iterator.next().setTheme(color);
        }
    }

    private void springOut() {
//        hideWaitingProgress();
//
//        if(mFromPush) {
//            //jump
//            doPushJump();
//            mFromPush = false;
//            return;
//        }

        final boolean showGuide = mGuideLayout.getChildCount() > 0;
        if(showGuide) {
            mGuideLayout.setAlpha(0f);
            mGuideLayout.setVisibility(View.VISIBLE);
        }

        ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
        anim.setDuration(1000);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float fraction = (float) animation.getAnimatedValue();

                if(showGuide) {
                    mGuideLayout.setAlpha(1-fraction);
                } else {
                    mBlurview.setAlpha(fraction);
                }
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(showGuide) {

                } else {
                    mBlurview.setOverlayColor(getResources().getColor(R.color.blur_color));

                    updateTheme();
                    springImg();
                }
            }
        });
        anim.start();
    }

    private void onGuideDismiss() {
        ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
        anim.setDuration(1000);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float fraction = (float) animation.getAnimatedValue();
                mBlurview.setAlpha(fraction);
                mGuideLayout.setAlpha(fraction);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mBlurview.setOverlayColor(getResources().getColor(R.color.blur_color));
                mGuideLayout.setVisibility(View.GONE);

                updateTheme();
                springImg();
            }
        });
        anim.start();
    }

    private void addDivider() {
        View view = new View(context);
        setBgWithRes(view, R.color.divider_color);
        int space = getResources().getDimensionPixelOffset(R.dimen.widget_margin);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1);
        params.leftMargin = space;
        params.rightMargin = space;
        mScrollContent.addView(view, params);
    }

    private void springImg() {
        //use 4/5*screenwidth instead
//        if(mScrollContent != null && mScrollContent.getChildCount() > 0) {
//            int itemHeight = mScrollContent.getChildAt(0).getHeight();
//            if(itemHeight > 0) {
//                targetHeight = getHeight() - itemHeight;
//
//                if (mScrollHeader != null) {
//                    LinearLayout.LayoutParams paramsTop = (LinearLayout.LayoutParams) mScrollHeader.getLayoutParams();
//                    paramsTop.height = targetHeight;
//                    mScrollHeader.setLayoutParams(paramsTop);
//                }
//
//                RelativeLayout.LayoutParams topParams = (RelativeLayout.LayoutParams) mBlurTop.getLayoutParams();
//                topParams.height = targetHeight;
//                mBlurTop.setLayoutParams(topParams);
//            }
//        }
        ValueAnimator springAnimatior = ValueAnimator.ofFloat(SCALE_INT, 1f);
        springAnimatior.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                if(mBgContainer != null) {
                    mBgContainer.setScaleX(value);
                    mBgContainer.setScaleY(value);
                }
                mSplash.setScaleY(value);
                mSplash.setScaleX(value);
            }
        });
        springAnimatior.setDuration(ANI_DURATION*3);

        float mTranslateY = SysUtil.getScreenHeight(context)*0.1f;
        ValueAnimator translateAnim = ValueAnimator.ofFloat(mTranslateY, 0);
        translateAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                if(mBgContainer != null) {
                    mBgContainer.setTranslationY(value);
                }
                mSplash.setTranslationY(value);
            }
        });
        translateAnim.setDuration(ANI_DURATION);

        mBlurview.setTranslationY(screenHeight);
        mBlurview.setAlpha(1f);
        ObjectAnimator translateUser = ObjectAnimator.ofFloat(mUsercenterImgLayout, "translationY", mUsercenterImgLayout.getHeight(), 0);
        translateUser.setDuration(ANI_DURATION);
        translateUser.setStartDelay(ANI_DURATION * 3 / 2);
        translateUser.setInterpolator(new OvershootInterpolator());

        final int mScrollLayoutHeight = mScrollview.getHeight();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f, 0);
        valueAnimator.setDuration(ANI_DURATION);
        valueAnimator.setStartDelay(ANI_DURATION / 2);
        valueAnimator.setInterpolator(new OvershootInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                float fBlur = targetHeight + (screenHeight - targetHeight) * value;
                float fScroll = (mScrollLayoutHeight - targetHeight) * value;
                mBlurview.setTranslationY(fBlur);
                mBlurview.invalidate();
                mScrollview.setTranslationY(fScroll);
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(mPositionManager != null) {
                    mPositionManager.reportItemsPosition();
                    mPositionManager.storeListenerPositions(0);
                }
                if (mScrollHeader != null)
                    mScrollHeader.startAnimIn();

                topMaskIn();

                //动画结束后开始上报数据
                AubeStatisticTool.getInstance(getContext()).upload();

                if(mViewPager != null)
                    mViewPager.startAutoScroll(true);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(springAnimatior, translateAnim, valueAnimator, translateUser);
        mSet.start();
    }

    private void topMaskIn() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(mBlurTop, "alpha", 0, 1);
        anim.setDuration(500);
        anim.start();
    }

    private void manageUserCenter() {
        if(mScrollview.getVisibility() == View.VISIBLE) {
            setImgWithRes(mUsercenterImg, R.drawable.icon_mainclose);
            manageUserLayout(true);
        } else {
            setImgWithRes(mUsercenterImg, R.drawable.icon_grzx);
            manageUserLayout(false);
        }
    }

    private void manageUserLayout(final boolean show) {
        ObjectAnimator scrollAnim = ObjectAnimator.ofFloat(mScrollview, "alpha", show ? 1 : 0, show ? 0 : 1);
        scrollAnim.setDuration(USERLAYOUT_DURATION);

        ObjectAnimator userAnim = ObjectAnimator.ofFloat(mUsercenterLayout, "alpha", show ? 0 : 1, show ? 1 : 0);
        userAnim.setDuration(USERLAYOUT_DURATION/2);
        if(show)
            userAnim.setStartDelay(USERLAYOUT_DURATION/2);

        ObjectAnimator userTranslateAnim = ObjectAnimator.ofFloat(mUsercenterLayout, "translationY", show ? 200 : 0, show ? 0 : 200);
        userTranslateAnim.setDuration(USERLAYOUT_DURATION/2);
        if(show)
            userTranslateAnim.setStartDelay(USERLAYOUT_DURATION/2);

        ObjectAnimator blurTranslationAnim = null;
        float translationY = mBlurview.getTranslationY();
        float lastTranslationY = targetHeight - mLastScrollY;
        if(lastTranslationY < 0)
            lastTranslationY = 0;

        ObjectAnimator maskTranslationAnim = null;
        float translationMaskY = mBlurTop.getTranslationY();

        if(show) {
            if(translationY > 0) {
                blurTranslationAnim = ObjectAnimator.ofFloat(mBlurview, "translationY", translationY, 0);
                maskTranslationAnim = ObjectAnimator.ofFloat(mBlurTop, "translationY", translationMaskY, -targetHeight);
            }
        } else {
            if(lastTranslationY > 0) {
                blurTranslationAnim = ObjectAnimator.ofFloat(mBlurview, "translationY", 0, lastTranslationY);
                maskTranslationAnim = ObjectAnimator.ofFloat(mBlurTop, "translationY", -targetHeight, translationMaskY);
            }
        }

        AnimatorSet set = new AnimatorSet();
        if(blurTranslationAnim == null)
            set.playTogether(scrollAnim, userAnim, userTranslateAnim);
        else {
            blurTranslationAnim.setDuration(USERLAYOUT_DURATION);
            blurTranslationAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    mBlurview.invalidate();
                }
            });
            set.playTogether(scrollAnim, userAnim, userTranslateAnim, blurTranslationAnim, maskTranslationAnim);
        }
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                if(show) {
                    mUsercenterLayout.setAlpha(0f);
                    mUsercenterLayout.setVisibility(View.VISIBLE);
                    rotateIcon();
                } else {
                    mScrollview.setAlpha(0f);
                    mScrollview.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if(show) {
                    mScrollview.setVisibility(View.GONE);
                    mUsercenterImg.setRotation(0);
                } else {
                    mUsercenterLayout.setVisibility(View.GONE);
                }
            }

        });
        set.start();
    }

    private void rotateIcon() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(mUsercenterImg, "rotation", 0, 180);
        anim.setDuration(USERLAYOUT_DURATION/2);
        anim.start();
    }

    public void getData(final boolean update) {
        HashMap<String, String> params = new HashMap<>();
        params.put("templateCode", TEMPLATE_INDEX);
        params.put(OpenApi.API_METHOD, OpenApi.HOME_DETAIL);
        BFJSONRequest request = new BFJSONRequest(HomeCategoryModel.class, params, new Response.Listener<HomeCategoryModel>() {
            @Override
            public void onResponse(HomeCategoryModel response) {
                if(update) {
                    refreshData(response);
                } else {
                    if (mBridge != null)
                        mBridge.onReady();

                    setupModules(response);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }

            @Override
            public void onStart() {

            }
        });
        HttpRequestLoader.getInstance(context).startHttpLoader(request);
    }

    @Override
    public void initData() {
        getData(false);
    }

    /**
     * see HOST
     * PushSetting.PUSH_REGIST_SUCCESS
     * UserUtil.LOGOUT
     * UserUtil.LOGIN_SUCCESS
     * Constant.MEMBERENCODE_ILLEGAL
     * @param data
     */
    @Override
    public void update(Object data) {
        if(data == null || !(data instanceof String))
            return;
        String action = (String) data;
        switch (action) {
            case UserUtil.LOGOUT:
                if(mUserLayout != null)
                    mUserLayout.update();
                //update other pluginstate
                updatePluginData();
                break;
            case UserUtil.LOGIN_SUCCESS:
                if(mUserLayout != null)
                    mUserLayout.update();
                //reload data and update other pluginstate
                getData(true);
                break;
            case Constant.MEMBERENCODE_ILLEGAL:
                if(mUserLayout != null)
                    mUserLayout.update();
                break;
            case "PUSH_REGIST_SUCCESS":
                if(mUserLayout != null)
                    mUserLayout.update();
                break;
        }
    }

    private void updatePluginData() {
        if(mDLLayouts != null) {
            Iterator<DLLayout> iterator = mDLLayouts.values().iterator();
            while (iterator.hasNext())
                iterator.next().update();
        }
    }

    private void refreshData(HomeCategoryModel data) {
        if(mDLLayouts != null && data != null && data.data != null) {
            for(Category category : data.data) {
                if(mDLLayouts.containsKey(category.getModelCode())) {
                    mDLLayouts.get(category.getModelCode()).update(category);
                }
            }
        }
    }

    @Override
    public void onResume() {
        if(mViewPager != null)
            mViewPager.startAutoScroll(true);
        if(mDLLayouts != null) {
            Iterator<DLLayout> iterator = mDLLayouts.values().iterator();
            while (iterator.hasNext())
                iterator.next().onResume();
        }
    }

    @Override
    public void onPause() {
        if(mViewPager != null)
            mViewPager.startAutoScroll(false);
    }

    @Override
    public void onDestroy() {
        if(mDLLayouts != null) {
            Iterator<DLLayout> iterator = mDLLayouts.values().iterator();
            while (iterator.hasNext())
                iterator.next().onDestroy();
        }
    }

    @Override
    public boolean onBackPressed() {
        if(mGuideLayout.getVisibility() == View.VISIBLE) {
            onGuideDismiss();
            return true;
        }

        if(mUsercenterLayout.getVisibility() == View.VISIBLE) {
            if(mUserLayout != null && mUserLayout.onBackPressed()) {
                return true;
            }
            setImgWithRes(mUsercenterImg, R.drawable.icon_grzx);
            manageUserLayout(false);
            return true;
        }
        return super.onBackPressed();
    }

    @Override
    public void onReady() {
        springOut();
    }

    public void attachViews(View... view){
        if(view != null && view.length > 0) {
            mBlurview = (BlurViewDecorator) view[0];
            mSplash = view[1];
            mBgContainer = (FrameLayout) view[2];
        }
    }

    private static final String TYPE_ACTOR = "actor";
    private static final String TYPE_LIST = "moreList";
    private static final String TYPE_VIDEO = "playVideo";

    /**
     * video:msg:{"showid":"1925","leftRightAngle":"","cameraType":"NORMAL","videoTitle":"幕后访谈首次公开","picurl":"http://static02.aube-tv.com/upload/images/video/201610/s_62d12424_1579e199397__7ffb.PNG","type":"playVideo","videoid":"14405","videoDesc":"第十三期 | 预告"}
     * 首页:msg:{"type":"index"}
     * 首页运营模块:msg:{"modelCode":"episode","templateCode":"index","subModelCode":"BlackMagic","type":"moreList"}
     * msg:{"modelCode":"actor_week_rank","templateCode":"index","subModelCode":"weekrank","type":"moreList"}
     * msg:{"modelCode":"stagePhoto","templateCode":"index","subModelCode":"2026","type":"moreList"}
     * 嘉宾:msg:{"headPicture":"http://static02.aube-tv.com/upload/images/actor/201607/s53361575_155c548fdfe__7fec.jpg","relatedId":"2019","type":"actor","actorName":"杨烁"}
     * 嘉宾运营:msg:{"modelCode":"episode","relatedId":"2019","templateCode":"actor","subModelCode":"2222","type":"moreList"}
     * @param mPushParams
     */
    @Override
    public void executePushEvent(String mPushParams) {
        try {
            if(mBridge == null)
                return;

            JSONObject jsonObject = new JSONObject(mPushParams);
            String actionType = jsonObject.optString("type");

            DLIntent intent = null;
            if (TYPE_ACTOR.equalsIgnoreCase(actionType)) {
                intent = new DLIntent("com.aube.plugin.origin", CharacterActivity.class.getName());
                intent.putExtra("ACTOR", buildCharacter(jsonObject));
                mBridge.openPluginActivity(intent);
            } else if (TYPE_LIST.equalsIgnoreCase(actionType)) {
                Category category = buildCategory(jsonObject);
                if (category != null) {
                    if ("stagephoto".equalsIgnoreCase(category.modelCode)) {
                        intent = new DLIntent("com.aube.plugin.gallery", "com.aube.plugin.gallery.GalleryListActivity");
                        intent.putExtra("GALLERY", category);
                    } else if ("episode".equalsIgnoreCase(category.modelCode)) {
                        intent = new DLIntent("com.aube.plugin.origin", VideoListActivity.class.getName());
                        intent.putExtra("CATEGORY", category);
                    } else if ("actor_week_rank".equalsIgnoreCase(category.modelCode)) {
                        intent = new DLIntent("com.aube.plugin.rank", "com.aube.plugin.rank.WeekRankActivity");
                        intent.putExtra("INTENT_CATEGORY", createCategory());
                        intent.putExtra("INTENT_COLOR", PluginPackageManager.getInstance().getTheme().getThemeColor());
                    }

                    if(intent != null)
                        mBridge.openPluginActivity(intent);
                }
            } else if (TYPE_VIDEO.equalsIgnoreCase(actionType)) {
                mBridge.onClickToVideo(buildVideo(jsonObject));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Character buildCharacter(JSONObject object) {
        Character character = new Character();
        character.actorName = object.optString("actorName");
        character.relatedId = object.optString("relatedId");
        return character;
    }

    private CategorySimple buildCategorySimple(JSONObject object) {
        CategorySimple categorySimple = new CategorySimple();
        categorySimple.templateType = object.optString("templateCode");
        categorySimple.relatedId = object.optString("relatedId");
        categorySimple.modelCode = object.optString("modelCode");
        categorySimple.subModelCode = object.optString("subModelCode");
        return categorySimple;
    }

    private Category buildCategory(JSONObject object) {
        Category category = new Category();
        category.templateType = object.optString("templateCode");
        category.relatedId = object.optString("relatedId");
        category.modelCode = object.optString("modelCode");
        category.subModelCode = object.optString("subModelCode");
        return category;
    }

    private ChannelDetail buildVideo(JSONObject object) {
        ChannelDetail channel = new ChannelDetail();
        channel.cameraType = object.optString("cameraType");
        channel.leftRightAngle = object.optString("leftRightAngle");
        channel.updownAngle = object.optString("updownAngle");
        channel.videoDesc = object.optString("videoDesc");
        channel.videono = object.optString("videono");
        channel.videoid = object.optString("videoid");
        channel.videoTitle = object.optString("videoTitle");
        channel.showid = object.optString("showid");
//        channel.picurl = object.optString("picurl");
        return channel;
    }

    private CategorySimple createCategory() {
        CategorySimple categorySimple = new CategorySimple();
        categorySimple.modelCode = "actor_week_rank";
        categorySimple.subModelCode = "weekrank";
        categorySimple.templateType = "index";
        return categorySimple;
    }

}
